<div id="tournament-template" class="tournament hidden">
	    <div class="header-tournament-live row-fluid">
	    	<div class="country span11"></div>
	    </div>
	    <div class="body-tournament-live"></div>
</div>
<div id="match-template" class="match hidden" data-static-id="">
	    <div class="header-match-live row-fluid">
	    	<div class="datetime span3"></div>
	    	<div class="localteam span3"><a class="team-popover" title="ciao" rel="popover" data-placement="left" ></a></div>
	    	<div class="score span2"></div>
	    	<div class="visitorteam span3"><a class="team-popover" title="ciao" rel="popover" data-placement="left" ></a></div>
	    </div>
	    <div class="body-match-live"></div>
</div>
<div id="event-template" class="event hidden">
</div>
<div id="event-row-template" class="event-row row-fluid hidden">
  <div class="tdMinute span3"></div>
  <div class="tdlocalteam span3"></div>
  <div class="tdScore span2"></div>
  <div class="tdvisitorteam span3"></div>
</div>

<table id="lineups-template" class="table table-hover hidden">
      <thead>
        <tr>
          <th><?php echo __("Numero"); ?></th>
          <th><?php echo __("Giocatore"); ?></th>
        </tr>
      </thead>
      <tbody>
          	<tr id="lineups-row-template"><td class="lineups-number"></td><td class="lineups-player"></td></tr>
      </tbody>
</table>  


<div class="progress progress-striped">
	<div id='countdown' class="bar" style="width: 0%;"></div>
</div>
<button id="start-stop" class="btn btn-mini pull-right">stop</button>
	
<div id="tournaments" class="" data-country='<?php echo $country; ?>' ></div>

<script>

	var countdown = new Countdown($('#countdown'),60,refresh);
	var countdownTimer = $.timer(function() {countdown.execute();},1000,true);

	$(document).ready(function() {
		var interval = 1000 * 20; // where X is your every X seconds
		refresh();
		$('#start-stop').click(function(){
			if ($('#start-stop').html()=='stop') {
				countdownTimer.pause();
				$('#start-stop').html('start');
			} else {
				countdownTimer.play();
				$('#start-stop').html('stop');
			}
		});

		$(document).on('click', ".team-popover", function() {
			// recupero altre infomrazioni inerenti alla squadra per il match corrente
			country = $('#tournaments').data('country');
			match_static_id = $(this).parent().parent().data('static-id');
			console.log('match_static_id');
			$.ajax({ type: "GET", url: "<?php echo $this->webroot;?>Feed/getCommentaries/"+country
			    , dataType: "json"
			    , success: function(data) {
			    	if(data.success) {
						  $.ajax({ type: "GET", url: data.url
						    , dataType: "xml"
						    , success: function(xml) {
								console.log('getCommentaries');
						      $(xml).find('category').each(function() {
						      	writeLineups($(this));
						      });
							}
							, error: function(request, error, tipo_errore) { setFlash(error+': '+ tipo_errore, 'error'); }
						  });
				    } else
				    	setFlash(data.message, data.level);
				}
			});
			
			$(this).popover({title: 'Formazione',
		                    html: true,
		                    content : '<div id="popOverBox">Your Text Here</div>'
							});
		});

	});
	
	function refresh() {
		  country = $('#tournaments').data('country');
		  $.ajax({ type: "GET", url: "<?php echo $this->webroot;?>Feed/getLive/"+country
		    , dataType: "json"
		    , success: function(data) {
		    	if(data.success) {
					  $.ajax({ type: "GET", url: data.url
					    , dataType: "xml"
					    , success: function(xml) {
					      	$('#tournaments').empty();
					      $(xml).find('category').each(function() {
					      	writeTournament($(this));
					      });
						}
						, error: function(request, error, tipo_errore) { setFlash(error+': '+ tipo_errore, 'error'); }
					  });
		    		
			    } else
			    	setFlash(data.message, data.level);
			}
		  });
	}
	
	function lastMatchs(formatted_date) {
		var t_date = new Date(formatted_date.replace(/(\d{2})\.(\d{2})\.(\d{4})/,'$3-$2-$1'));
		var today=new Date();
		var ventiquattroOre = 1000*60*60*48
		var yesterday=today.getTime() - ventiquattroOre;
		// console.log(yesterday + ' - ' + t_date.getTime());
		// console.log(yesterday <= t_date.getTime());
		return (yesterday <= t_date.getTime());
	}

	
	function writeTournament(tournament) {
		if (lastMatchs(tournament.find('matches').attr('formatted_date'))) {
			tournamentElement = $('#tournament-template').clone();
			HeaderTournamentElement = tournamentElement.children('.header-tournament-live');
			HeaderTournamentElement.children('.country').html(tournament.attr('name'));
			HeaderTournamentElement.children('.date').html(tournament.find('matches').attr('formatted_date'));
	        tournament.find('match').each(function() {
				if (lastMatchs($(this).attr('formatted_date')))
					tournamentElement.children('.body-tournament-live').append(writeMatch($(this)));
	        });
			tournamentElement.removeAttr('id');
			tournamentElement.removeClass('hidden');
			tournamentElement.appendTo($('#tournaments'));
		}
	}
	
    function writeMatch(match) {
		matchElement = $('#match-template').clone();
		localteam = match.find('localteam');
		visitorteam = match.find('visitorteam');
		// console.log(match.attr('static_id'));
		matchElement.data('static-id', match.attr('static_id'));
		// console.log(matchElement.data('static-id'));
		matchElement.children('.header-match-live').children('.localteam').children('a').html(localteam.attr('name'));
		matchElement.children('.header-match-live').children('.score').html('[' + localteam.attr('goals') + ' - ' + visitorteam.attr('goals') + ']');
		matchElement.children('.header-match-live').children('.visitorteam').children('a').html(visitorteam.attr('name'));
		matchElement.children('.header-match-live').children('.datetime').html(match.attr('formatted_date') + ' - ' + match.attr('time') + ' (' + match.attr('status') + ')');
		eventElement = $('#event-template').clone();
        match.find('event').each(function() {
			writeEvent(eventElement,$(this));
        });
        matchElement.children('.body-match-live').append(eventElement);
		eventElement.removeAttr('id');
		eventElement.removeClass('hidden');
		matchElement.removeAttr('id');
		matchElement.removeClass('hidden');
        return matchElement;
    }

    function writeEvent(eventElement, eventData) {
		eventRowElement = $('#event-row-template').clone();
		// console.log(eventElement.find('tr').html());
		eventRowElement.children('.td'+eventData.attr('team')).html(eventData.attr('type') + ' ' + eventData.attr('player'));
		eventRowElement.children('.tdMinute').html(eventData.attr('minute')+"'");
		eventRowElement.children('.tdScore').html(eventData.attr('result'));
		eventRowElement.removeAttr('id');
		eventRowElement.removeClass('hidden');
		eventElement.append(eventRowElement);
        // return eventElement;
    }

    function writeLineups(LineupsElement, lineupsData) {
		eventRowElement = $('#event-row-template').clone();
		// console.log(eventElement.find('tr').html());
		eventRowElement.children('.td'+eventData.attr('team')).html(eventData.attr('type') + ' ' + eventData.attr('player'));
		eventRowElement.children('.tdMinute').html(eventData.attr('minute')+"'");
		eventRowElement.children('.tdScore').html(eventData.attr('result'));
		eventRowElement.removeAttr('id');
		eventRowElement.removeClass('hidden');
		eventElement.append(eventRowElement);
        // return eventElement;
    }

</script>